package dk.ahp.galgelegapp;


import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
//import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class GalgeActivity extends Activity implements TextWatcher , SensorEventListener/*, OnSharedPreferenceChangeListener */{
	private EditText et;
	private TextView tv, status, debug;
	private ImageView iv;
	private SharedPreferences prefs;

	private SensorManager sm = null;
	private float shock = 0;
	private float max=0, min=10000;
	private long lastResetTime=0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_galge);
        et = (EditText) findViewById(R.id.gæt);
        et.addTextChangedListener(this);
        tv = (TextView) findViewById(R.id.synligt_ord);
        status = (TextView) findViewById(R.id.status);
        debug = (TextView) findViewById(R.id.debugView1);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
//        prefs.registerOnSharedPreferenceChangeListener(this);
        iv = (ImageView) findViewById(R.id.imageView1);
        setStatusText();
    	tv.setText(GalgeApplication.getGalgeLogik().synligtOrd);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.activity_galge, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    	case R.id.itemPrefs:
    		startActivity(new Intent(this, PrefsActivity.class));
    		break;
    	case R.id.wordList:
    		startActivity(new Intent(this, WordList.class));
    		break;
    	}
    	return true;
    }
    
    @Override
    public void afterTextChanged(Editable s) {
    	Log.d("afterTextChanged", s.toString());
        if (s!=null && s.length()>1){// Kun et bogstav i edit text feltet.
                 et.setText(s.subSequence(1, s.length()));
                 if (!GalgeApplication.getGalgeLogik().SpilletSlut())
                	 et.setSelection(1);
                 return;
        }
        GalgeApplication.getGalgeLogik().gaetBogstav(s.toString());
        tv.setText(GalgeApplication.getGalgeLogik().synligtOrd);
        
        if(GalgeApplication.getGalgeLogik().SpilletSlut())
        {
        	InputMethodManager imm = (InputMethodManager)getSystemService(
        			Context.INPUT_METHOD_SERVICE);
        	imm.hideSoftInputFromWindow(et.getWindowToken(), 0); //fjern tastatur
        	if(1==s.length()) // og fjern text fra edit text feltet.
        	{
        		et.setText(s.subSequence(0, 0));
        		et.setSelection(0);
        	}
        }
        setStatusText();
    }

    // bør flyttes til GalgeLogik
    private void storePrefs(){
    	Log.d("storePrefs", "Gemmer alt.");
    	prefs.edit().putString("ordet", GalgeApplication.getGalgeLogik().ordet).commit();
    	prefs.edit().putString("synligtOrd", GalgeApplication.getGalgeLogik().synligtOrd).commit();
    	prefs.edit().putInt("korrekteBogstaver", GalgeApplication.getGalgeLogik().korrekteBogstaver).commit();
    	prefs.edit().putInt("forkerteBogstaver", GalgeApplication.getGalgeLogik().forkerteBogstaver).commit();
    	prefs.edit().putBoolean("sidsteBogstavVarKorrekt", GalgeApplication.getGalgeLogik().sidsteBogstavVarKorrekt).commit();
    	prefs.edit().putBoolean("spilletErVundet", GalgeApplication.getGalgeLogik().spilletErVundet).commit();
    	prefs.edit().putBoolean("spilletErTabt", GalgeApplication.getGalgeLogik().spilletErTabt).commit();
    	prefs.edit().putString("brugteBogstaver", GalgeApplication.getGalgeLogik().brugteBogstaver.toString()).commit();//Commit it all.
    	Log.d("storePrefs", GalgeApplication.getGalgeLogik().brugteBogstaver.toString());
    }
    
    // bør flyttes til GalgeLogik
    private void restorePrefs(){
       	Log.d("restorePrefs", "start med at nulstille galgeLogik");
       	Log.d("restorePrefs prefs", prefs.getString("listKey", "V0"));
       	GalgeApplication.getGalgeLogik().nulstil(prefs.getString("listKey", "V0"));
       	GalgeApplication.getGalgeLogik().ordet = prefs.getString("ordet", "");
       	GalgeApplication.getGalgeLogik().synligtOrd = prefs.getString("synligtOrd", "");
       	GalgeApplication.getGalgeLogik().korrekteBogstaver = prefs.getInt("korrekteBogstaver", 0);
    	GalgeApplication.getGalgeLogik().forkerteBogstaver = prefs.getInt("forkerteBogstaver", 0);
    	GalgeApplication.getGalgeLogik().sidsteBogstavVarKorrekt = prefs.getBoolean("sidsteBogstavVarKorrekt", false);
    	GalgeApplication.getGalgeLogik().spilletErVundet = prefs.getBoolean("spilletErVundet", false);
    	GalgeApplication.getGalgeLogik().spilletErTabt = prefs.getBoolean("spilletErTabt", false);
    	String array = prefs.getString("brugteBogstaver", "");
    	GalgeApplication.getGalgeLogik().brugteBogstaver.clear();
    	if(array.length()>2) {
    		String[] tmp = array.substring(1, array.length()-1).split(", ");
    		for (String s : tmp) {
    			GalgeApplication.getGalgeLogik().brugteBogstaver.add(s);
    		}
    	}
    	setStatusText();
    	tv.setText(GalgeApplication.getGalgeLogik().synligtOrd);
    }
    
    private void reset() {
    	Log.d("reset","");
    	Log.d("reset prefs", prefs.getString("listKey", "V0"));
    	GalgeApplication.getGalgeLogik().nulstil(prefs.getString("listKey", "V0"));
    	//setStatusImage(); bliver kaldt fra setStatusText
    	setStatusText();
    	tv.setText(GalgeApplication.getGalgeLogik().synligtOrd);
    }
    
    private void setStatusText() {
    	Log.d("setStatusText", "");
        if(GalgeApplication.getGalgeLogik().spilletErVundet)
        {
        	status.setText(R.string.vinderText);
        }
        else if (GalgeApplication.getGalgeLogik().spilletErTabt)
        {
        	status.setText(R.string.taberText);
        }
        else
        {
        	status.setText((GalgeApplication.getGalgeLogik().GætTilbage()) + getResources().getString(R.string.gæt_endnu));
        	setStatusImage();
        }
    }
    
	private void setStatusImage() {
		Log.d("setStatusImage", "");
		switch(GalgeApplication.getGalgeLogik().forkerteBogstaver)
		{
		case 0:
			iv.setImageResource(R.drawable.galge);
			break;
		case 1:
			iv.setImageResource(R.drawable.forkert1);
			break;
		case 2:
			iv.setImageResource(R.drawable.forkert2);
			break;
		case 3:
			iv.setImageResource(R.drawable.forkert3);
			break;
		case 4:
			iv.setImageResource(R.drawable.forkert4);
			break;
		case 5:
			iv.setImageResource(R.drawable.forkert5);
			break;
		case 6:
			iv.setImageResource(R.drawable.forkert6);
			break;
		default:
			Log.e("setStatusImage", "galgeLogik.forkerteBogstaver has illegal value");
		}
	}

    @Override
    public void onResume()
    {
    	super.onResume();
    	Log.d("onResume", "onResume");
    	restorePrefs();
    	setStatusText();
    	tv.setText(GalgeApplication.getGalgeLogik().synligtOrd);
    	sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 1000000000);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Log.d("onPause", "onPause");
        sm.unregisterListener(this);

        //luk tastaturet.
        InputMethodManager imm = (InputMethodManager)getSystemService(
    			Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(et.getWindowToken(), 0); //fjern tastatur

    	et.setText("");
    	
        storePrefs();
    }    
    
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {}

	@Override
	public void onSensorChanged(SensorEvent event) 
	{
		float[] values = event.values;
        //Log.d("onSensorChanged", "" + event.sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
	 	if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
	 	{
        	String debugStr;
        	
        	float newAccel = Math.abs(values[0]) + Math.abs(values[1]) + Math.abs(values[2]);
        	if (newAccel > max)
        		max = newAccel;
        	if(newAccel < min)
        		min = newAccel;
        	if (Math.abs(newAccel - shock) > 1)
        	{
        		shock = newAccel;
        		debugStr = "Sum" + (Math.abs(values[0]) + Math.abs(values[1]) + Math.abs(values[2]));
        		debugStr += "\nMax: " + max + "\nMin: " + min;
        		debug.setText(debugStr);
        	}
        	long sysTime = System.currentTimeMillis();
        	long diff = sysTime-lastResetTime;
        	if(newAccel>30 && (diff>2000)) //reset ikke flere gange i sekundet.
        	{
        		Log.d("onSensorChanged", "kalder reset");
        		lastResetTime = sysTime;
        		reset();
        		InputMethodManager imm = (InputMethodManager)getSystemService(
            			Context.INPUT_METHOD_SERVICE);
            	imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
        		et.setText("");
        		storePrefs();
        	}
        }            
	}
/*
	@Override
	public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
		Log.d("onSharedPreferenceChanged", "arg1 " + arg1);
		String value = prefs.getString("navn", "navn ikke sat.");
		String K2 = prefs.getString("listKey", "defValue");
		value += "\n" + getResources().getString(R.string.sværhedsgrad) + " " + K2;
		value += "\n" + arg0.getString("navn", "navn ikke sat.");
		K2 = arg0.getString("listKey", "defValue");
		value += "\n" + getResources().getString(R.string.sværhedsgrad) + " " + K2;
		debug.setText(value );
	}
*/
}
